const fs = require('@/utils/fs_promise.js')
const config = require('@/store/config.js')
const commands = require('./commands.js')
const hookers = require('./hook.js')
const stat = require('@/store/statistics.js')

module.exports = {
    async init() {
        var [err, ret] = await to(fs.access(config.repo_dir, fs.constants.R_OK | fs.constants.W_OK))
        if (err && err.errno != -2) {
            console.error(err.message)
            process.exit(err.errno)
        }
        if (err) {
            var [err, ret] = await to(fs.mkdir(config.repo_dir, { recursive: true }))
            if (err) {
                console.error(err.message)
                process.exit(err.errno)
            }
        }

        stat.clear()
        for (let repo of config.repos) {
            var [err, {flag, message}] = await to(commands.git_clone(repo.url, repo.path))
            stat.append({
                flag,
                command: 'git clone',
                reponame: repo.name,
                target: repo.url,
                message,
            })

            if (flag == ERROR.OK) {
                await hookers.exec(repo)
            }
        }
        stat.print()
    },
    async list() {
        stat.clear()
        for (let repo of config.repos) {
            await hookers.stat(repo)
        }
        stat.print()
    },
    async status() {
        stat.clear()
        for (let repo of config.repos) {
            var [err, {flag, message}] = await to(commands.git_status(repo.path))
            stat.append({
                flag,
                command: 'git status',
                reponame: repo.name,
                target: repo.path,
                message,
            })
        }
        stat.print()
    },
    async sync() {
        stat.clear()
        for (let repo of config.repos) {
            var [err, {flag}] = await to(commands.git_sync(repo.path))
            stat.append({
                flag,
                command: 'git sync',
                reponame: repo.name,
                target: repo.path,
            })
        }
        stat.print()
    },
}
